/*
 * Image_dir.h
 *
 *  Created on: May 10, 2010
 *      Author: Soheil Damangir
 */

#include <stdio.h>
#include <cstdlib>
#include <iostream>
#include <string.h>
#include <fstream>
#include <dirent.h>
#include "log.h"
#include "image.h"
#include "Image_dir.h"

using namespace kthrobot;

Dir_Iter::Dir_Iter(const char*dir)
{
  if (strcmp(dir, "") != 0)
    open_dir(dir);
}
void Dir_Iter::reset()
{
  closedir(pDIR);
  pDIR=opendir(this->dir);
}
void Dir_Iter::open_dir(const char*dir)
{
  strcpy(this->dir,dir);
  reset();
}
char* Dir_Iter::get_next_file()
{
  strcpy(last_file,dir);
  while((entry = readdir(pDIR)))
  {
    if( strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0 )
    {
      strcpy(last_file_name, entry->d_name);
      strcat(last_file, last_file_name) ;
      return last_file;
    }
  }
  return NULL;
}
Dir_Iter::~Dir_Iter()
{
  closedir(pDIR);
}

Image_Iter::Image_Iter(const char* dir): diter(dir)
{
}
void Image_Iter::open_dir(const char* dir)
{
  diter.open_dir(dir);
}
Image* Image_Iter::next_image()
{
  char* f_name = diter.get_next_file();
  if (!f_name)
  {
    diter.reset();
    f_name =diter.get_next_file();
    Log::Write("Processing %s",f_name);
    image.LoadPPM(string(f_name));
  }else
  {
    Log::Write("Processing %s",f_name);
    image.LoadPPM(string(f_name));
  }
  return &image;
}
